<template>
  <div class="page-login">
    <van-form ref="formRef" @failed="onFailed" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="model.phone"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          maxlength="11"
          :error-message="phoneErrorMessage"
          :rules="[
            { required: true, message: '请填写手机号' },
            {
              pattern: /^1\d{10}$/,
              message: '请输入正确的手机号'
            }
          ]"
        >
          <template #button>
            <van-button size="small" type="primary" :disabled="isDisabled" @click="sendSmsCode">
              {{ isCountDown ? count : '发送验证码' }}
            </van-button>
          </template>
        </van-field>
        <van-field
          v-model="model.code"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 登录 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import { smsCodeLogin, smsCodeSend } from '@/api'
import type { FormInstance } from 'vant'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const formRef = ref<FormInstance | null>(null)

const model = reactive({
  phone: '', // 手机号
  code: '' // 验证码
})
const defaultCount = 60
// 倒计时，秒数
const count = ref(defaultCount)
// 是否倒计时
const isCountDown = ref(false)
// 开始倒计时
function startCountDown() {
  isCountDown.value = true
  const time = setInterval(() => {
    if (count.value === 0) {
      clearInterval(time)
      count.value = defaultCount
      isCountDown.value = false
    } else {
      count.value--
    }
  }, 1000)
}
// 手机号错误文本
const phoneErrorMessage = ref('')
// 处理 phoneErrorMessage 的值
async function chuliPhoneErrorMessage(errors?: { name: string; message: string }[]) {
  if (!errors) {
    // 如果 errors 不存在，自行获取
    await formRef.value?.validate().catch((err) => (errors = err))
  }
  // find 手机号的错误
  const error = errors?.find((item) => item.name === '手机号')
  // 给 phoneErrorMessage 赋值
  if (error) {
    phoneErrorMessage.value = error.message
  }
}

// 发送验证码是否禁用
const isDisabled = computed(() => {
  return !/^1\d{10}$/.test(model.phone) || isCountDown.value
})

// 发送验证码
async function sendSmsCode() {
  try {
    await smsCodeSend({ imgCode: '', imgKey: '', mobile: model.phone, type: '1' })
    // 开始倒计时
    startCountDown()
  } catch (error: any) {
    phoneErrorMessage.value = error.message
  }
}

// 提交表单且验证不通过后触发
function onFailed({ errors }: any) {
  chuliPhoneErrorMessage(errors)
}

// 提交表单且验证通过后触发
async function onSubmit() {
  // 调用登录接口
  const result = await smsCodeLogin({
    extra: {},
    imgCode: '',
    imgKey: '',
    mobile: model.phone,
    smsCode: model.code
  })
  // 将用户信息写入到 pinia 仓库中
  userStore.setUserInfo(result)

  // 获取 url 地址的 redirect
  const redirect = route.query.redirect as string
  if (redirect) {
    router.replace(redirect)
  } else {
    router.back()
  }
}

function onPhoneBlur() {
  chuliPhoneErrorMessage()
}
</script>

<style scoped>
.page-login {
  box-sizing: border-box;
  padding-top: 100px;
  height: 100%;
  background-color: #f4f4f4;
  overflow: hidden;
}
</style>
